<script setup lang="ts">
import { message } from 'ant-design-vue'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import { driverReturnOrderApi } from '@/api/business/storage/returnwarehouse-api'
import printModal from '@/components/business/print-modal/index.vue'
import dayjs from 'dayjs'
import { useEnums } from '@/hooks/plugins/useEnums'
const { getDescByValue } = useEnums()

type QuantityData = {
  large: number
  middle: number
  small: number
}

type GoodsItem = {
  serial: number
  brand: string
  goods_name: string
  box_code: string
  bottle_code?: string
  quantity: string // 如 "11箱11排11瓶"
  quantity_data: QuantityData
  remark?: string
}

type DealerGroup = {
  dealer_name: string
  goods_data: GoodsItem[]
  dealer_total_large: number
  dealer_total_middle: number
  dealer_total_small: number
  dealer_total_string: string
}

type PickingData = {
  header: {
    task_no: string
    into_warehouse: string
    return_no: string
    into_date: string
  }
  dealer_groups: DealerGroup[]
  summary: {
    total_large: number
    total_middle: number
    total_small: number
    total_string: string
  }
  footer: {
    preparer: string // 制单人
    driver_phone: string
    remark?: string
  }
}

const visible = ref(false)
const open = ref(false)
const printData = ref<PickingData | null>(null)
const recordId = ref<string | number>('')
const driverWarehouse = ref({})
const intoWarehouse = ref({})
const print_count = ref(0)
const showDrawer = async (record) => {
  recordId.value = record.id
  dataDetail()
  driverWarehouse.value = record.driverWarehouse
  intoWarehouse.value = record.intoWarehouse
  try {
    const res = await driverReturnOrderApi.driverReturnOrderPrintDetail({ id: record.id })
    printData.value = res.data
    visible.value = true
  } catch (error) {
    message.error(error.msg || '数据加载失败')
  }
}

defineExpose({ showDrawer })

const dataDetail = async () => {
   try {
    const res = await driverReturnOrderApi.driverReturnOrderOrder({ id: recordId.value, is_sign_detail: 0 })
    print_count.value = res.data.printLog.print_count
  } catch (error) {
    message.error(error.msg || '数据加载失败')
  }
}

const onClose = () => {
  visible.value = false
  printData.value = null
}
const loading = ref(false)

const usePrint = () => {
  const onPrint =async  () => {
    loading.value = true

    try {
    dataDetail()
  } catch (e) {
    console.error('更新打印次数失败', e)
    loading.value = false
    return
  }
  await nextTick()

    const LODOP = getLodop()
    if (!LODOP) {
      open.value = true
      loading.value = false
      return
    }

    LODOP.PRINT_INITA('0mm', '0mm', '241mm', '93mm', '回库单')
    LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', '回库单')
    LODOP.ADD_PRINT_HTM(10, '3%', '94%', '100%', document.querySelector('#print-table')?.outerHTML)
    LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')
    // LODOP.ADD_PRINT_TEXT(0, '5%', 196, 20, '县链云仓')
    LODOP.SET_PRINT_STYLEA(0, 'ItemType', 0)
    LODOP.NewPageA()
    LODOP.PREVIEW()
    loading.value = false
  }

  return { onPrint }
}

const { onPrint } = usePrint()

const handleModalClose = () => {
  open.value = false
}
</script>

<template>
  <printModal :open="open" @cancel="handleModalClose" />
  <a-drawer title="回库单打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>

    <table id="print-table" border="0" cellspacing="0" cellpadding="0" width="100%" style="border-collapse: collapse; font-size: 11pt">
       <tbody>
        <tr>
     <td colspan="7">
            <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700"
              >回库单
            </div>
            <font style="position: absolute; right: 0; top: 0">
              <span tdata="pageNO" format="#">#</span>
              <span>/</span>
              <span tdata="pageCount" format="#">##</span>
            </font>
          </td>
  </tr>
        </tbody>
      <tbody>
        <!-- 头部信息 -->
        <tr>
          <td colspan="7">
           出:{{ driverWarehouse?.name }}<span v-if="driverWarehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', driverWarehouse?.attribute_type) }})</span>&nbsp;&nbsp;&nbsp;&nbsp;
            <span
              >入:{{ intoWarehouse?.name }}<span v-if="intoWarehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', intoWarehouse?.attribute_type) }})</span></span
            >&nbsp;&nbsp;&nbsp;&nbsp; 
            <span>日期:{{ printData?.header?.into_date }}</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>打印次数:{{ print_count || 0 }}&nbsp;&nbsp;&nbsp;&nbsp;打印日期: {{ dayjs(Date()).format('YYYY-MM-DD HH:mm:ss') }}&nbsp;&nbsp;&nbsp;&nbsp;单号:{{ printData?.header?.return_no }}</span
            >
          </td>
        </tr>

        <!-- 数据行：遍历所有经销商 -->
        <template v-for="dealer in printData?.dealer_groups" :key="dealer.dealer_name">
          <!-- 经销商分组标题行 -->
          <tr>
            <td colspan="7" style="border: 1pt solid #000; font-weight: 700"> 经销商:{{ dealer?.dealer_name }} </td>
          </tr>
          <!-- 表格列头 -->
          <tr>
            <th width="8%" style="border: 1pt solid #000">序号</th>
            <th width="15%" style="border: 1pt solid #000">品牌</th>
            <th width="22%" style="border: 1pt solid #000">商品名称</th>
            <th width="10%" style="border: 1pt solid #000">数量</th>
            <th width="15%" style="border: 1pt solid #000">箱码</th>
            <th width="15%" style="border: 1pt solid #000">瓶码</th>
            <th width="10%" style="border: 1pt solid #000">备注</th>
          </tr>

          <!-- 商品明细行 -->
          <tr v-for="(goods,index) in dealer.goods_data" :key="goods.serial">
            <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ goods?.brand }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ goods?.goods_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ goods?.quantity }}</td>
            <td style="border: 1pt solid #000; text-align: center">
              {{ goods?.box_code }}
            </td>
            <td style="border: 1pt solid #000; text-align: center">
              {{ goods?.bottle_code || '-' }}
            </td> 
            <td style="border: 1pt solid #000; text-align: center">{{ goods?.remark || '' }}</td>
          </tr>
        </template>

        <!-- 汇总行 -->
        <tr>
          <td style="border: 1pt solid #000; text-align: center">总计</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000; text-align: center">{{ printData?.summary?.total_string }}</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
        </tr>
        <!-- 页脚信息 -->
        <tr>
          <td colspan="7" style="font-weight: 700"> 制单: {{ printData?.footer?.preparer }}&nbsp;&nbsp;&nbsp;&nbsp; 司机电话:{{ printData?.footer?.driver_phone }}&nbsp;&nbsp;&nbsp;&nbsp; 备注:{{ printData?.footer?.remark || '-' }} </td>
        </tr>
      </tbody>
    </table>

    <template #footer>
      <div class="flex justify-end">
        <a-button @click="onClose" style="margin-right: 8px">关闭</a-button>
        <a-button :loading="loading" type="primary" @click="onPrint">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
